<script setup>
import { Plus, Search } from '@element-plus/icons-vue'
import useChannel from '@/store/channel'
import { addChatChannel } from '@/assets/api/dialog-group'
import { ElMessage } from 'element-plus'
import useUser from '@/store/user'
import { removeChannel } from '@/utils/dialog-utils'
import useEventBus from '@/use/use-event-bus'
import { useEventListener } from '@vueuse/core/index'
import useFold from '@/store/fold'
import { match } from 'pinyin-pro'

const channelStore = useChannel()
const userStore = useUser()
const router = useRouter()
const route = useRoute()
const eventBus = useEventBus()
const currentTag = ref(null)
const personnelSelectionVisible = ref(false)
const channelName = ref('')

// 频道过滤
const filterChannelList = computed(() => {
  const list = channelStore.channelList.filter(
    (i) =>
      i.collapse === (isCollapse.value ? 1 : 2) &&
      (i.name?.includes(channelName.value) || !!match(i.name || '', channelName.value)?.length)
    //(i) => (currentTag.value === 'all' || i.type === currentTag.value) && i.name?.includes(msgName.value)
  )
  // 返回全部频道
  if (currentTag.value?.value === 999) return list
  // 返回有未读消息的频道
  if (currentTag.value?.value === 101) {
    const filterList = Array.from(channelStore.countStatisticsMap)
      .filter((i) => i[1].rootMsgCount > 0)
      .map((i) => i[0])
    // 免打扰不算在未读中
    return list.filter((i) => filterList.includes(i.id) && i.dndFlag !== 1)
  }
  // 返回@我的频道
  if (currentTag.value?.value === 102) {
    const filterList = Array.from(channelStore.countStatisticsMap)
      .filter((i) => i[1].mentionCount > 0)
      .map((i) => i[0])
    return list.filter((i) => filterList.includes(i.id))
  }
  if (currentTag.value?.channelIdList) {
    return list.filter((i) => currentTag.value.channelIdList.includes(i.id))
  }
  // 其他标签频道
  return list.filter((i) => {
    return i.type === currentTag.value?.value
  })
})

// 聊天分组控制
const tagListVisible = ref(false)
// 快捷筛选标签
const searchTag = ref([
  { label: '全部', value: 999 },
  { label: '未读', value: 101 },
  { label: '@我', value: 102 },
  { label: '单聊', value: 1 },
  { label: '群聊', value: 5 },
])
// 是否是折叠消息列表
const isCollapse = ref(false)
// 右键菜单是否显示
const contextmenuShow = ref(false)

// 当前右键频道
const currentChannel = ref(null)
const showMenuItem = ref(false)

eventBus.on('createChannel', () => {
  personnelSelectionVisible.value = true
})

eventBus.on('channelCreated', (data) => {
  toChannel(data)
})

function setCurrentTag(tag) {
  tagListVisible.value = false
  currentTag.value = tag
}

// 每个分组的数量
const tagCount = computed(() => {
  const list = channelStore.channelList.filter(
    (i) => i.collapse === (isCollapse.value ? 1 : 2) && i.name?.includes(channelName.value)
  )
  const fn = (arr) => {
    return arr.reduce((count, item) => {
      count += channelStore.countStatisticsMap.get(item.id)?.rootMsgCount || 0
      return count
    }, 0)
  }
  const countObj = {
    999: fn(list),
    101: fn(
      list.filter(
        (i) =>
          Array.from(channelStore.countStatisticsMap)
            .filter((i) => i[1].rootMsgCount > 0)
            .map((i) => i[0])
            .includes(i.id) && i.dndFlag !== 1
      )
    ),
    102: fn(
      list.filter((i) =>
        Array.from(channelStore.countStatisticsMap)
          .filter((i) => i[1].mentionCount > 0)
          .map((i) => i[0])
          .includes(i.id)
      )
    ),
  }
  searchTag.value.forEach((item) => {
    if (!Object.prototype.hasOwnProperty.call(countObj, item.value)) {
      countObj[item.value] = fn(list.filter((i) => i.type === item.value))
    }
  })
  return countObj
})

function dialogue(data) {
  if (data.removeFlag) {
    removeChannel(data.channelId, {
      content: `你已被移出${data.name}`,
      title: '移出群聊',
    })
    return
  }
  if (data.deleteFlag) {
    removeChannel(data.channelId, {
      content: '该群聊已解散',
      title: '群聊解散',
    })
    return
  }
  if (!data.removeFlag && !data.deleteFlag) {
    toChannel(data)
  }
}

const foldStore = useFold()

function toChannel(data) {
  channelStore.setDialog(data)
  router.push({
    path: route.path,
    query: {
      ...route.query,
      channelId: data.id,
    },
  })
  foldStore.setHideChatContent(false)
  if (channelStore.channelMsgMap.get(data.id)) {
    eventBus.emit('dialogScrollBottom')
  }
}

/**
 * 创建频道
 */
function createGroup(members) {
  const userList = members.filter((i) => !i.children)
  if (userList.length < 1) {
    return ElMessage.error('选择频道成员')
  }
  userList.push(userStore.userInfo)
  const channelMembers = Array.from(new Set(userList.map((i) => i.userId)))
  const name = userList
    .slice(0, Math.min(3, userList.length))
    .map((i) => i.nickName)
    .join(',')
  addChatChannel({
    channelMembers,
    name,
    type: channelMembers.length > 2 ? 5 : 1,
  }).then((res) => {
    if (res.code === 200) {
      personnelSelectionVisible.value = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

onMounted(() => {
  useEventListener('click', () => {
    if (showMenuItem.value) {
      contextmenuShow.value = true
    } else {
      contextmenuShow.value = false
      currentChannel.value = null
    }
  })
  currentTag.value = searchTag.value[0]
})
</script>

<template>
  <div class="channel-list">
    <div class="channel-list-search">
      <el-input placeholder="搜索对话" v-model="channelName" clearable>
        <template #prefix>
          <el-icon color="#FF9000" size="16"><Search></Search></el-icon>
        </template>
      </el-input>
      <div class="channel-add">
        <el-icon @click="personnelSelectionVisible = true"><Plus /></el-icon>
      </div>
    </div>
    <div class="channel-search-tag">
      <div class="channel-search-tag-list">
        <div
          class="channel-search-tag-item"
          :class="{ active: currentTag?.value === item.value }"
          v-for="(item, index) in searchTag.slice(0, 4)"
          :key="index"
          @click="setCurrentTag(item)">
          <span>
            {{ `${item.label}${tagCount[item.value]}` }}
          </span>
        </div>
      </div>
    </div>
    <div class="channel-list-body">
      <ChannelCard v-for="item in filterChannelList" :key="item.id" :data="item" @click="dialogue"></ChannelCard>
    </div>
    <PersonnelSelection
      v-model="personnelSelectionVisible"
      :disabled-method="(user) => user.id === userStore.userInfo.userId"
      @submit="createGroup"></PersonnelSelection>
  </div>
</template>

<style scoped lang="scss">
.channel-list {
  @include use-flex();
  flex-direction: column;
  height: 100%;
  padding: 10px;
  flex-shrink: 0;
  border-right: 1px solid var(--elp-border-color);
  .channel-list-search {
    @include use-flex(center);
    padding: 10px 4px 10px 5px;
    margin-bottom: 5px;

    .channel-add {
      @include use-flex(center, center);
      cursor: pointer;
      height: 32px;
      width: 32px;
      border-radius: 6px;
      flex-shrink: 0;
      margin-left: 10px;
      background-color: var(--elp-fill-color-light);
    }
    :deep(.elp-input) {
      .elp-input__wrapper {
        border-radius: 5px;
        background-color: var(--elp-bg-color-page);
        border: 0;
        box-shadow: none;
        .elp-input__prefix-inner {
          width: 25px;
          & > :last-child {
            margin-right: 0;
          }
        }
      }
    }
  }
  .channel-search-tag {
    @include use-flex(center, space-between);
    position: relative;
    padding-bottom: 10px;
    overflow: hidden;
    .channel-search-tag-list {
      @include use-flex(center, space-between);
      width: calc(100% - 24px);
      .channel-search-tag-item {
        @include use-flex(center);
        cursor: pointer;
        font-size: 14px;
        padding: 0 7px;
        border-radius: 10px;
        white-space: nowrap;
        &.active {
          background-color: var(--elp-color-info-light-8);
        }
      }
    }
  }
  .collapse-title {
    display: flex;
    align-items: center;
    background-color: var(--elp-bg-color-page);
    margin-top: 10px;
    font-size: 14px;
    border-bottom: 1px solid var(--elp-bg-color-page);
    padding: 8px 0 8px 2px;
    font-weight: 600;
    border-radius: 3px;
    cursor: pointer;
  }
  .channel-list-body {
    flex: 1;
    overflow-y: auto;
  }
  :deep(.group-text) {
    margin: 30px 0 10px;
  }
}
</style>
<style lang="scss">
.channel-group-contextmenu {
  position: absolute;
  font-size: 12px;
  padding: 10px;
  width: 130px;
  border-radius: 5px;
  background-color: var(--elp-bg-color);
  box-shadow: var(--elp-box-shadow);
  z-index: 1;
  .menu-item {
    font-size: 12px;
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 5px;
    &:hover {
      background-color: #d4d8e080;
    }
    :focus-visible {
      outline: none;
    }
  }
  .elp-divider--horizontal {
    margin: 5px 0;
  }
}
.channel-group-popover {
  --elp-popover-padding: 0px;
  .tag-panel {
    padding: 10px;
    overflow-y: auto;
    .tag-panel-head {
      @include use-flex(center, space-between);
      font-size: 16px;
      font-weight: bold;
      padding-bottom: 10px;
      border-bottom: 1px solid #d4d8e0;
      .manage-btn {
        font-size: 12px;
        font-weight: normal;
        cursor: pointer;
      }
    }
    .tag-list {
      max-height: 300px;
      padding: 10px 0;
      .tag-item {
        @include use-flex(center, space-between);
        cursor: pointer;
        padding: 6px 10px;
        &:hover {
          font-weight: bold;
          color: #0d53ff;
          background: rgba(13, 83, 255, 0.1);
        }
      }
    }
  }
}
</style>
